package com.nwpu.server.learning.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nwpu.server.common.util.file.FileUtils;
import com.nwpu.server.learning.entity.FileEntity;
import com.nwpu.server.learning.entity.TaskEntity;
import com.nwpu.server.learning.enums.StatusEnum;
import com.nwpu.server.learning.service.FileService;
import com.nwpu.server.learning.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.List;

@Configuration
@EnableScheduling
public class ScheduleTaskConfiguration {
    private static final Logger log = LoggerFactory.getLogger(ScheduleTaskConfiguration.class);

    @Resource
    private TaskService taskService;

    @Autowired
    private FileService fileService;

    @Value(value = "${learning.file.dir}")
    private String dir;

    /**
     * @功能描述 定时任务 每天4点清理
     */
    @Scheduled(cron = "0 0 4 * * ?")
    private void cleanINEFFCTIONTask() {
        List<TaskEntity> list = taskService.list();

        for (TaskEntity taskEntity : list) {
            int status = taskEntity.getStatus();
            // 失效任务 运行失败任务定时清理
            if (status == StatusEnum.EXCEPTIONAL.getValue() || status == StatusEnum.CANCELLED.getValue() || status == StatusEnum.INTERRUPTED.getValue()) {
                // 数据库删除数据
                QueryWrapper<TaskEntity> taskQueryWrapper = new QueryWrapper<TaskEntity>().eq("id", taskEntity.getId());
                taskService.remove(taskQueryWrapper);
                QueryWrapper<FileEntity> fileQueryWrapper = new QueryWrapper<FileEntity>().eq("task_id", taskEntity.getId());
                fileService.remove(fileQueryWrapper);

                // 服务器删除文件
                FileUtils.deleteFile(dir + taskEntity.getId() + "." + "json");
                log.info("删除任务:{}", taskEntity.getId());
            }
        }

    }
}
